const express = require('express')
const router = express.Router()
const { users, token } = require('../db')


// 登录接口
router.post('/login',async (req, res)=>{
    const {username, password} = req.body
    if (!username || !password) {
        res.json({code: 0, msg:"请正确填写账号或密码"})
        return
    }
    try {
        const userinfo = await users.find({username,password})
        if (userinfo.length > 0) {
            const creToken = (Math.random() + new Date().getTime()).toString()
            await token.create({token:creToken})
            res.json({code: 1, msg:'登录成功',token:creToken})
        } else {
            res.json({code:'0',msg:"当前用户不存在"})
        }
    } catch (error) {
        res.json({code:0, msg:'用户名或密码错误'})
    }
})


//注册接口
router.post('/register',async (req, res)=>{
    const {username, password} = req.body
    if (!username || !password) {
        res.json({code: 0, msg:"请正确填写账号或密码"})
        return
    }
    try {
        const userinfo = await users.create({username,password})
        res.json({code: 1, msg:'注册成功'})
    } catch (error) {
        res.json({code:0, msg:'未知错误'})
    }
})

//admin login
router.post('/admin',async (req, res)=>{
    const {username, password} = req.body
    if (!username || !password) {
        res.json({code: 0, msg:"请正确填写账号或密码"})
        return
    }
    try {
        const userinfo = await users.find({username,password,vip:888})
        if (userinfo.length > 0) {
            const creToken = (Math.random() + new Date().getTime()).toString()
            await token.create({token:creToken})
            res.json({code: 1, msg:'登录成功',token:creToken})
        } else {
            res.json({code:'0',msg:"当前用户不存在"})
        }
    } catch (error) {
        res.json({code:0, msg:'用户名或密码错误'})
    }
})

module.exports = router